package processes

import (
	"encoding/json"
	"fmt"
	"go_code/project01_basic/chapter15_qq/client/model"
	"go_code/project01_basic/chapter15_qq/message"
)

//创建在线用户信息列表
var onlineUsers = make(map[int]*UserProcess, 10)
var CurUser model.CurUser

func OutputOnlineUser() {
	fmt.Println("当前在线用户列表:")
	for _, v := range onlineUsers {
		if v.UserStatus == message.UserOnline {
			fmt.Println("用户:", v.NickName)
		}
	}
}

func UpdateUserStatus(mes *message.Message) {
	notify := message.NotifyUserStatusMes{}
	err := json.Unmarshal([]byte(mes.Data), &notify)
	if err != nil {
		fmt.Println("Unmarshal NotifyUserStatusMes err=", err)
	}
	_, ok := onlineUsers[notify.UserId]
	if !ok {
		up := &UserProcess{
			UserId:     notify.UserId,
			NickName:   notify.UserName,
			UserStatus: message.UserOnline,
		}
		onlineUsers[notify.UserId] = up
		fmt.Printf("%v上线了~\n", notify.UserName)
	}
}

func AddLoginUser(id int, up *UserProcess) {
	onlineUsers[id] = up
}

func OutputGroupMse(mes *message.Message) {
	smsMes := message.SmsMes{}
	err := json.Unmarshal([]byte(mes.Data), &smsMes)
	if err != nil {
		fmt.Println("Unmarshal SmsMes err=", err)
	}
	fmt.Printf("%v[群发]: %v\n", smsMes.UserName, smsMes.Content)
}

func OutputPrivateMse(mes *message.Message) {
	smsPrivateMes := message.SmsPrivateMes{}
	err := json.Unmarshal([]byte(mes.Data), &smsPrivateMes)
	if err != nil {
		fmt.Println("Unmarshal smsPrivateMes err=", err)
	}
	fmt.Printf("%v[私聊]: %v\n", smsPrivateMes.UserName, smsPrivateMes.Content)
}

func DeleteOfflineUser(mes *message.Message) {
	offlineMes := message.OfflineMes{}
	err := json.Unmarshal([]byte(mes.Data), &offlineMes)
	if err != nil {
		fmt.Println("Unmarshal offlineMes err=", err)
	}
	delete(onlineUsers, offlineMes.UserId)
}
